package com.horoscope.astrology.zodiac.signs.free.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.work.*
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.material.tabs.TabLayout
import com.google.firebase.iid.FirebaseInstanceId
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.bean.FCMResultBean
import com.horoscope.astrology.zodiac.signs.free.fragment.ArticleFragment
import com.horoscope.astrology.zodiac.signs.free.fragment.AstrologyFragment
import com.horoscope.astrology.zodiac.signs.free.fragment.HoroscopeFragment
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.service.NameWork
import com.horoscope.astrology.zodiac.signs.free.service.QuoteWork
import com.horoscope.astrology.zodiac.signs.free.utils.*
import com.horoscope.astrology.zodiac.signs.free.utils.Logger
import com.horoscope.astrology.zodiac.signs.free.view.RatingDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit


class MainActivity : BaseActivity() {

    private val userBean = AppSettingManager.readObject("user_info")
    private var todayTime: String? = null
    private var mArticleCurrentTitle = "Hot"// 主要用于判断是否是新的一天。article显示红点
    private var mTabLayout: TabLayout? = null
    private var horoscopeFrgm: HoroscopeFragment? = null
    private var astrologyFrgm: AstrologyFragment? = null
    private var articleFrgm: ArticleFragment? = null
    private var ratingDialog: RatingDialog? = null
    private val mFragments = arrayOfNulls<Fragment>(3)

    private val isShowDialog: Boolean
        get() {
            val openTime = AppSettingManager.readInt("app_open", 0)
            val currentTime = System.currentTimeMillis()
            val timeDiff = currentTime - AppSettingManager.readLong("installTime", 0)
            // 安装是否够三天 &&
            if (timeDiff >= three_day && (openTime - 3) % 10 == 0 && !userBean!!.gradeStatus) {
                showDiyDialog()
                return true
            }
            return false
        }

    private val mHandler = MainActivityHandler(this@MainActivity)

    class MainActivityHandler(activity: MainActivity) : Handler() {
        private val mActivity: WeakReference<MainActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (mActivity.get() == null) return

//            val myActivity: MainActivity? = mActivity.get()


        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        // 判断是否弹出评分对话框
        showScoreDialog()
        // 进程保活 1PX
        keepProcess()
        // 上报FCM token
        putFCMToken()
//        IntegrationHelper.validateIntegration(this)
        startQuoteWork()
        // 设置name、relation、birthchat闹钟
        if (AppSettingManager.readInt("isFirstOpen", 0) == 0) {
            // 创建定时任务
            otherAlarm()
            GlobalScope.launch(Dispatchers.Main) {
                delay(3000L)
                AppSettingManager.saveInt(1, "isFirstOpen")
            }
        }
    }

    private fun otherAlarm() {
        // 启动条件（最大延迟，触发更新）
        val constraints = Constraints.Builder()
            .setTriggerContentMaxDelay(5, TimeUnit.MINUTES)
            .setTriggerContentUpdateDelay(20, TimeUnit.MINUTES)
            .build()

        val name = AppSettingManager.readInt("name_result", 0)
        val relation = AppSettingManager.readInt("relation_result", 0)
        val birth = AppSettingManager.readInt("birth_chat", 0)

        // 判断指定三个功能是否使用过,分别启动对应页面的通知任务
        if (name == 0) {
            val nameRequest = PeriodicWorkRequest
                .Builder(NameWork::class.java, 2, TimeUnit.DAYS)
                .setConstraints(constraints)
                .setInputData(
                    Data.Builder().putString("workName", "NameAlarm")
                        .putIntArray("num", intArrayOf(9, 10, 11)).build()
                )
                .build()
            WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                "NameAlarm",
                ExistingPeriodicWorkPolicy.KEEP, nameRequest
            )
        }
        if (relation == 0) {
            val relationRequest = PeriodicWorkRequest
                .Builder(NameWork::class.java, 2, TimeUnit.DAYS)
                .setConstraints(constraints)
                .setInputData(
                    Data.Builder().putString("workName", "RelationAlarm")
                        .putIntArray("num", intArrayOf(12, 13, 14)).build()
                )
                .build()
            WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                "RelationAlarm",
                ExistingPeriodicWorkPolicy.KEEP, relationRequest
            )
        }
        if (birth == 0) {
            val birthRequest = PeriodicWorkRequest
                .Builder(NameWork::class.java, 2, TimeUnit.DAYS)
                .setConstraints(constraints)
                .setInputData(
                    Data.Builder().putString("workName", "BirthChatAlarm")
                        .putIntArray("num", intArrayOf(15, 16, 17)).build()
                )
                .build()
            WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                "BirthChatAlarm",
                ExistingPeriodicWorkPolicy.KEEP, birthRequest
            )
        }
    }

    private fun startQuoteWork() {
        // 启动条件（最大延迟，触发更新）
        val constraints = Constraints.Builder()
            .setTriggerContentMaxDelay(5, TimeUnit.MINUTES)
            .setTriggerContentUpdateDelay(20, TimeUnit.MINUTES)
            .build()

        //获取一个builder
        val request = PeriodicWorkRequest
            .Builder(QuoteWork::class.java, 3, TimeUnit.HOURS)
            .setConstraints(constraints)
            .addTag("TestWork")
            .build()
        //插入worker队列，并且使用enqueueUniquePeriodicWork方法，防止重复
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            "QuoteAlarm",
            ExistingPeriodicWorkPolicy.KEEP, request
        )
    }

    private fun keepProcess() {
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.intent.action.SCREEN_OFF")
        intentFilter.addAction("android.intent.action.SCREEN_ON")
        intentFilter.addAction("android.intent.action.USER_PRESENT")
        registerReceiver(onePixelReceiver, intentFilter)
    }

    private fun showScoreDialog() {
        if (!isShowDialog) {
            activityShowAd("Interstitial_Splash")
        } else {//当horoscope页没有显示广告时，切换其它页面时需要补一次
            AppSettingManager.saveInt(1, "supplement")

        }
    }

    // 检索当前的FCM注册令牌（需要梯子！！！）
    private fun putFCMToken() {
        FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    Logger.debug("FCMToken", "getInstanceId failed${task.exception}")
                    return@OnCompleteListener
                }

                // Get new Instance ID token
                val token = task.result?.token
//                LiveEventBus.get("FCM", String::class.java).post(token)
                NetworkEngine.postFCMToken(token!!,
                    userBean!!.constellationName,
                    SysUtils.getCurrentTimeZone(), object : NetworkListener<FCMResultBean>() {
                        override fun onSuccess(t: FCMResultBean) {
                            Log.d("FCMToken", "onSuccess")
                        }
                    })
                Log.e("FCMToken", token)
            })
    }


    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
        unregisterReceiver(onePixelReceiver)
    }


    private fun initView() {
        horoscopeFrgm = HoroscopeFragment()
        astrologyFrgm = AstrologyFragment()
        articleFrgm = ArticleFragment()

        mFragments[0] = horoscopeFrgm
        mFragments[1] = astrologyFrgm
        mFragments[2] = articleFrgm

        todayTime = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
        mTabLayout = findViewById(R.id.bottom_tab_layout)

        mTabLayout!!.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                when (tab.position) {
                    0 -> {
                        // 在Home页进行了点击行为
                        FlurryEventUtil.putDataToEvent(
                            EventType.TYPE_TAB_CLICK,
                            "type",
                            "Horoscope"
                        )
                        changeFragment(mFragments[0], "horoscope")
                    }
                    1 -> {
                        FlurryEventUtil.putDataToEvent(
                            EventType.TYPE_TAB_CLICK,
                            "type",
                            "Astrology"
                        )
                        changeFragment(mFragments[1], "astrology")
                    }
                    2 -> {
                        FlurryEventUtil.putDataToEvent(EventType.TYPE_TAB_CLICK, "type", "Article")
                        changeFragment(mFragments[2], "article")
                    }
                }
                changeTabIcon(tab.position)
                isAddAd()  // 补充广告位
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {}

            override fun onTabReselected(tab: TabLayout.Tab) {
                // 双击刷新数据
                if (tab.position == 0 && SysUtils.isFastClick() && horoscopeFrgm != null) {
                    horoscopeFrgm!!.loadData()
                } else if (tab.position == 2 && SysUtils.isFastClick() && articleFrgm != null) {
                    articleFrgm!!.doubleClick()
                }

            }
        })


        for (i in 0..2) {
            val view = LayoutInflater.from(this).inflate(R.layout.custom_view, null)
            val icon = view.findViewById<ImageView>(R.id.tab_content_image)
            val nineRed = view.findViewById<TextView>(R.id.nine_plus)
            icon.setImageResource(mTabRes[i])
            handleRedPoint(i, nineRed)
            val text = view.findViewById<TextView>(R.id.tab_content_text)
            text.text = mTabText[i]
            mTabLayout!!.addTab(mTabLayout!!.newTab().setCustomView(view))
        }

        pushPage(intent)
    }

    private fun changeTabIcon(position: Int) {
        for (i in 0 until mTabLayout!!.tabCount) {
            val view = mTabLayout!!.getTabAt(i)!!.customView
            val icon = view!!.findViewById<ImageView>(R.id.tab_content_image)
            val text = view.findViewById<TextView>(R.id.tab_content_text)
            val nine = view.findViewById<TextView>(R.id.nine_plus)
            if (i == position) {
                icon.setImageResource(mTabResPressed[i])
                if (i == 2) {
                    showBadge(nine)
                }
                text.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
            } else {
                icon.setImageResource(mTabRes[i])
                text.setTextColor(
                    ContextCompat.getColor(
                        this@MainActivity,
                        R.color.white_3
                    )
                )
            }
        }
    }

    private fun showBadge(red: TextView) {
        red.visibility = View.INVISIBLE
        todayTime?.let {
            AppSettingManager.saveString(it, "SignInTime")

        }
    }

    private fun handleRedPoint(i: Int, red: TextView) {
        if (i == 2 && isNeedBadge()) {
            red.visibility = View.VISIBLE
        }
    }

    private fun isNeedBadge(): Boolean {
        return if (todayTime == AppSettingManager.readString("SignInTime", "2017-04-08")
        ) { //如果两个时间段相等
            false
        } else {
            return true
        }
    }


    fun setArticleCurrentTitle(title: String) {
        mArticleCurrentTitle = title
        articleFrgm?.notifyAd()

    }

    fun getArticleCurrentTitle() = mArticleCurrentTitle

    private fun isAddAd() {
        if (AppSettingManager.readInt("supplement", 0) == 1) {
            activityShowAd("Supplement")
        }
    }

    // 返回键 退出应用
    private var mPressedTime: Long = 0
    override fun onBackPressed() {
        val mNowTime = System.currentTimeMillis()
        if ((mNowTime - mPressedTime) > 2000) {
            ToastUtil.showText(this, getString(R.string.text_back))
            mPressedTime = mNowTime;
        } else {
            startActivity(Intent(this@MainActivity, BackActivity::class.java))
            finish()
        }
    }

    private fun changeFragment(fragment: Fragment?, tag: String) {
        val transaction = supportFragmentManager.beginTransaction()
        if (fragment != null)
            if (!fragment.isAdded && supportFragmentManager.findFragmentByTag(tag) == null) {
                transaction.add(R.id.home_container, fragment, tag)
                transaction.show(fragment)
            } else {
                for (frgm in mFragments) {
                    if (fragment != frgm) {
                        transaction.hide(frgm!!)
                    } else {
                        transaction.show(frgm)
                    }
                }
            }
        transaction.commitAllowingStateLoss()
    }

    companion object {
        private val mTabRes =
            intArrayOf(
                R.mipmap.tab_horoscope_no,
                R.mipmap.tab_astrology_no,
                R.mipmap.tab_article_no
            )
        private val mTabResPressed =
            intArrayOf(
                R.mipmap.tab_horoscope,
                R.mipmap.tab_astrology,
                R.mipmap.tab_article
            )
        private val mTabText = arrayOf("Horoscope", "Astrology", "Article")
        private const val three_day = (1000 * 3600 * 24 * 3).toLong()
    }

    private val onePixelReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                Intent.ACTION_SCREEN_OFF -> { // 屏幕关闭启动1像素Activity
                    val intent1 = Intent(this@MainActivity, ActivityOnePix::class.java)
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent1)
                }
                Intent.ACTION_SCREEN_ON -> { // 屏幕打开 结束1像素
                    sendBroadcast(Intent("finish"))

                }
            }
        }

    }

    // 自定义评分Dialog
    private fun showDiyDialog() {
        ratingDialog = RatingDialog(this)
        ratingDialog!!.setSureOnclickListener(object : RatingDialog.OnSureOnclickListener {
            override fun onSureClick() {
                FlurryEventUtil.putDataToEvent(EventType.TYPE_RATING_SURE, null, null)
                userBean!!.gradeStatus = true
                AppSettingManager.saveObject(userBean, "user_info")
                ratingDialog!!.dismiss()
                ProjectUtils.goToRating(this@MainActivity)
            }
        })
        ratingDialog!!.setNopeOnclickListener(object : RatingDialog.OnNopeOnclickListener {
            override fun onNopeClick() {
                ratingDialog!!.dismiss()
            }
        })
        ratingDialog!!.show()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        pushPage(intent)
    }

    private fun pushPage(intent: Intent?) {
        if (intent!!.getIntExtra("page", 0) == 2) {
            changeTabIcon(2)
            mTabLayout!!.getTabAt(2)!!.select()
        }
        if (intent.getIntExtra("page", 0) == 1) {
            changeTabIcon(1)
            mTabLayout!!.getTabAt(1)!!.select()
        }
    }
}
